export const deepCopy = (data) => {
  if (!data) return null
  return JSON.parse(JSON.stringify(data))
}

/**
 * 生成唯一的uuid值传回后台，genUUID(12, 16)
 */
export const genUUID = (len, radix) => {
  const chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  let i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    let r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

export const saveFile = (data, filename) => {
  const saveLink = document.createElementNS(
    'http://www.w3.org/1999/xhtml',
    'a'
  )
  saveLink.href = data
  saveLink.download = filename

  const event = document.createEvent('MouseEvents')
  event.initMouseEvent(
    'click',
    true,
    false,
    window,
    0,
    0,
    0,
    0,
    0,
    false,
    false,
    false,
    false,
    0,
    null
  )
  saveLink.dispatchEvent(event)
}

export const readFile = (file) => {
  const reader = new FileReader()
  reader.readAsText(file)
  return new Promise((resolve) => {
    reader.onload = function() {
      // console.log(typeof (this.result))
      resolve(JSON.parse(this.result))
    }
  })

}
// 节流：当持续触发事件时，保证一定时间段内只调用一次事件处理函数。减少触发频率
export const throttle = (fn, delay) => {
  let task = null
  return function() {
    if (!task) {
      const self = this
      const args = arguments
      task = setTimeout(function() {
        task = null
        fn.apply(self, args)
      }, delay)
    }
  }
}

export const debounce = (fn, delay) => {
  let task = null
  return function() {
    if (task) {
      // console.log('task', +new Date(), task)
      clearTimeout(task)
    }
    const self = this
    const args = arguments
    task = setTimeout(function() {
      fn.apply(self, args)
    }, delay)
  }
}

export const snapshot = {
  data: [],
  index: -1,
  isLock: false,
  record(record) {
    if (
      this.isLock ||
      JSON.stringify(record) === JSON.stringify(this.data[this.data.length - 1])
    ) {
      this.isLock = false
      return false
    }
    this.isLock = false
    console.info('添加快照', this.index)
    this.data[++this.index] = deepCopy(record)
    // 在 undo 过程中，添加新的快照时，要将它后面的快照清理掉
    if (this.index < this.data.length - 1) {
      this.data = this.data.slice(0, this.index + 1)
    }
  },
  // 重做
  redo() {
    if (this.index < this.data.length - 1) {
      this.isLock = true
      this.index++
      console.info('重做', this.index)
      return deepCopy(this.data[this.index])
    }
    return this.data[this.data.length - 1]
  },
  undo() {
    if (this.index > 0) {
      this.isLock = true
      this.index--
      console.info('撤销', this.index)
      return deepCopy(this.data[this.index])
    }
    return this.data[0]
  },
}
